package com.database.xinda.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yzycoc.common.api.vo.Result;
import com.database.xinda.service.ICmsMsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

/**
 * @program: cs-spring-cloud -> com.demo.controller
 * @description:
 * @author: XinDa2020
 * @create: 2021/6/1 14:14:51
 * @Version 1.0
 **/
@Api(tags="单元测试 模块：cs-cloud-demo")
@Controller
@Slf4j
@RequestMapping("/demo/cs/cloud")
public class CmsDemoController {
    @Autowired
    private ICmsMsService iCmsMsService;
    @ApiOperation("测试接口")
    @GetMapping(value = "/isok")
    @ResponseBody
    public Result<?> isOk() {
        log.info("获取请求内容");
        return Result.OK(UUID.randomUUID().toString());
    }



    @ApiOperation("测试数据链路")
    @GetMapping(value = "/msList")
    @ResponseBody
    public Result<?> msList(){
        return new Result<>().ok200(iCmsMsService.list());
    }

    /***
     * 服务降级
     * @return
     * @throws InterruptedException
     */

    @ApiOperation("服务降级")
    @GetMapping(value = "/isno")
    @ResponseBody
    @HystrixCommand(fallbackMethod = "helloisNoerror",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000")
    })
    public Result<?> isno() throws InterruptedException {
        //int a = 1/0;cdc
        log.info("获取请求内容isno");
        Thread.sleep(3000);
        return Result.OK(UUID.randomUUID().toString());
    }

    public Result<?> helloisNoerror(){
        return Result.error("error保存");
    }
    /****
     *  服务熔断
     */
    @ApiOperation("服务熔断")
    @GetMapping(value = "/paymetCircuit")
    @ResponseBody
    @HystrixCommand(fallbackMethod = "paymetCircuitError",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "1000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后

    })
    public Result<?> paymetCircuit() throws InterruptedException {
        //int a = 1/0;cdc
        log.info("获取请求内容isno");
        Thread.sleep(3000);
        return Result.OK(UUID.randomUUID().toString());
    }

    public Result<?> paymetCircuitError(){
        return Result.error("开启熔断机制");
    }

}
